home *** CD-ROM | disk | FTP | other *** search
/ Aminet 21 / Aminet 21 (1997)(GTI - Schatztruhe)[!][Oct 1997].iso / Aminet / gfx / show / gs_src_gs.lha / gs5.03 / interp.c < prev    next >
C/C++ Source or Header  |  1997-07-19  |  46KB  |  1,485 lines

  1. /* Copyright (C) 1989, 1996, 1997 Aladdin Enterprises.  All rights reserved.
  2.   
  3.   This file is part of Aladdin Ghostscript.
  4.   
  5.   Aladdin Ghostscript is distributed with NO WARRANTY OF ANY KIND.  No author
  6.   or distributor accepts any responsibility for the consequences of using it,
  7.   or for whether it serves any particular purpose or works at all, unless he
  8.   or she says so in writing.  Refer to the Aladdin Ghostscript Free Public
  9.   License (the "License") for full details.
  10.   
  11.   Every copy of Aladdin Ghostscript must include a copy of the License,
  12.   normally in a plain ASCII text file named PUBLIC.  The License grants you
  13.   the right to copy, modify and redistribute Aladdin Ghostscript, but only
  14.   under certain conditions described in the License.  Among other things, the
  15.   License requires that the copyright notice and this notice be preserved on
  16.   all copies.
  17. */
  18.  
  19. /* interp.c */
  20. /* Ghostscript language interpreter */
  21. #include "memory_.h"
  22. #include "string_.h"
  23. #include "ghost.h"
  24. #include "gsstruct.h"            /* for iastruct.h */
  25. #include "stream.h"
  26. #include "errors.h"
  27. #include "estack.h"
  28. #include "ialloc.h"
  29. #include "iastruct.h"
  30. #include "inamedef.h"
  31. #include "interp.h"
  32. #include "ipacked.h"
  33. #include "ostack.h"        /* must precede iscan.h */
  34. #include "strimpl.h"        /* for sfilter.h */
  35. #include "sfilter.h"        /* for iscan.h */
  36. #include "iscan.h"
  37. #include "idict.h"
  38. #include "isave.h"
  39. #include "istack.h"
  40. #include "iutil.h"        /* for array_get */
  41. #include "ivmspace.h"
  42. #include "dstack.h"
  43. #include "files.h"        /* for file_check_read */
  44. #include "oper.h"
  45. #include "store.h"
  46.  
  47. /*
  48.  * We may or may not optimize the handling of the special fast operators
  49.  * in packed arrays.  If we do this, they run much faster when packed, but
  50.  * slightly slower when not packed.
  51.  */
  52. #define PACKED_SPECIAL_OPS 1
  53.  
  54. /*
  55.  * Pseudo-operators (procedures of type t_oparray) record
  56.  * the operand and dictionary stack pointers, and restore them if an error
  57.  * occurs during the execution of the procedure and if the procedure hasn't
  58.  * (net) decreased the depth of the stack.  While this obviously doesn't
  59.  * do all the work of restoring the state if a pseudo-operator gets an
  60.  * error, it's a big help.  The only downside is that pseudo-operators run
  61.  * a little slower.
  62.  */
  63.  
  64. /* Imported operator procedures */
  65. extern int zop_add(P1(os_ptr));
  66. extern int zop_def(P1(os_ptr));
  67. extern int zop_sub(P1(os_ptr));
  68. /* Other imported procedures */
  69. extern int ztokenexec_continue(P1(os_ptr));
  70.  
  71. /* 
  72.  * The procedure to call if an operator requests rescheduling.
  73.  * This causes an error unless the context machinery has been installed.
  74.  */
  75. private int
  76. no_reschedule(void)
  77. {    return_error(e_invalidcontext);
  78. }
  79. int (*gs_interp_reschedule_proc)(P0()) = no_reschedule;
  80. /*
  81.  * The procedure to call for time-slicing.
  82.  * This is a no-op unless the context machinery has been installed.
  83.  */
  84. int
  85. no_time_slice_proc(void)
  86. {    return 0;
  87. }
  88. int (*gs_interp_time_slice_proc)(P0()) = no_time_slice_proc;
  89. /*
  90.  * The number of interpreter "ticks" between calls on the time_slice_proc.
  91.  * Currently, the clock ticks before each operator, and at each
  92.  * procedure return.
  93.  */
  94. int gs_interp_time_slice_ticks = 0x7fff;
  95.  
  96. /*
  97.  * Apply an operator.  We route all operator calls through a procedure when
  98.  * debugging.
  99.  */
  100. #ifdef DEBUG
  101. private int
  102. call_operator(int (*op_proc)(P1(os_ptr)), os_ptr op)
  103. {    int code = (*op_proc)(op);
  104.     return code;
  105. }
  106. #else
  107. #  define call_operator(proc, op) ((*(proc))(op))
  108. #endif
  109.  
  110. /* Forward references */
  111. private int estack_underflow(P1(os_ptr));
  112. private int interp(P2(ref *, ref *));
  113. private int interp_exit(P1(os_ptr));
  114. private void set_gc_signal(P2(int *, int));
  115. private int copy_stack(P2(const ref_stack *, ref *));
  116. private int oparray_pop(P1(os_ptr));
  117. private int oparray_cleanup(P1(os_ptr));
  118.  
  119. /* Stack sizes */
  120.  
  121. /* The maximum stack sizes may all be set in the makefile. */
  122.  
  123. /*
  124.  * Define the initial maximum size of the operand stack (MaxOpStack
  125.  * user parameter).  Currently this is also the block size for extending
  126.  * the operand stack, but this isn't guaranteed in the future.
  127.  */
  128. #ifndef MAX_OSTACK
  129. #  define MAX_OSTACK 800
  130. #endif
  131. /*
  132.  * The minimum block size for extending the operand stack is the larger of:
  133.  *    - the maximum number of parameters to an operator
  134.  *    (currently setcolorscreen, with 12 parameters);
  135.  *    - the maximum number of values pushed by an operator
  136.  *    (currently setcolortransfer, which calls zcolor_remap_one 4 times
  137.  *    and therefore pushes 16 values).
  138.  */
  139. #define min_block_ostack 16
  140. const int gs_interp_max_op_num_args = min_block_ostack;    /* for iinit.c */
  141.  
  142. /*
  143.  * Define the initial maximum size of the execution stack (MaxExecStack
  144.  * user parameter).
  145.  */
  146. #ifndef MAX_ESTACK
  147. #  define MAX_ESTACK 250
  148. #endif
  149. /*
  150.  * The minimum block size for extending the execution stack is the largest
  151.  * size of a contiguous block surrounding an e-stack mark, currently ???.
  152.  * At least, that's what the minimum value would be if we supported
  153.  * multi-block estacks, which we currently don't.
  154.  */
  155. #define min_block_estack MAX_ESTACK
  156.  
  157. /*
  158.  * Define the initial maximum size of the dictionary stack (MaxDictStack
  159.  * user parameter).  Again, this is also currently the block size for
  160.  * extending the d-stack.
  161.  */
  162. #ifndef MAX_DSTACK
  163. #  define MAX_DSTACK 20
  164. #endif
  165. /*
  166.  * The minimum block size for extending the dictionary stack is the number
  167.  * of permanent entries on the dictionary stack, currently 3.
  168.  */
  169. #define min_block_dstack 3
  170. uint min_dstack_size;        /* set by iinit.c */
  171.  
  172. /* Interpreter state variables */
  173. ref ref_systemdict;        /* set by iinit.c */
  174. ref ref_language_level;        /* 1 or 2, set by iinit.c */
  175.  
  176. /* See estack.h for a description of the execution stack. */
  177.  
  178. /* The logic for managing icount and iref below assumes that */
  179. /* there are no control operators which pop and then push */
  180. /* information on the execution stack. */
  181.  
  182. /* Stacks */
  183. /*
  184.  * We must create the stacks as legitimate 'objects' for the memory
  185.  * manager, so that the garbage collector can work with them.
  186.  */
  187. #define os_guard_under 10
  188. #define os_guard_over 10
  189. #define os_refs_size(body_size)\
  190.   (stack_block_refs + os_guard_under + (body_size) + os_guard_over)
  191. ref_stack o_stack;
  192. #define es_guard_under 1
  193. #define es_guard_over 10
  194. #define es_refs_size(body_size)\
  195.   (stack_block_refs + es_guard_under + (body_size) + es_guard_over)
  196. ref_stack e_stack;
  197. #define ds_refs_size(body_size)\
  198.   (stack_block_refs + (body_size))
  199. ref_stack d_stack;
  200.  
  201. /* Allocate the top blocks statically iff we are dealing with */
  202. /* a segmented architecture where this is important. */
  203. #if stacks_are_segmented
  204. private struct stk_ {
  205.     chunk_head_t head;
  206.     obj_header_t prefix;
  207.     ref bodies[os_refs_size(MAX_OSTACK) +
  208.            es_refs_size(MAX_ESTACK) +
  209.            ds_refs_size(MAX_DSTACK)];
  210.     ref padding;        /* for GC */
  211. } static_stacks;
  212. #endif
  213. extern_st(st_ref_stack);
  214. ref ref_static_stacks;        /* exported for GC */
  215. ref ref_ref_stacks[3];        /* exported for GC */
  216.  
  217. /* Stack pointers */
  218. ref *esfile;                /* cache pointer to currentfile */
  219. /* Cached dstack values are in idict.c. */
  220.  
  221. /* Extended types.  The interpreter may replace the type of operators */
  222. /* in procedures with these, to speed up the interpretation loop. */
  223. /****** NOTE: If you add or change entries in this list, */
  224. /****** you must change the three dispatches in the interpreter loop. */
  225. /* The operator procedures are declared in opextern.h. */
  226. #define tx_op t_next_index
  227. private const op_proc_p special_ops[] = {
  228.     zadd, zdef, zdup, zexch, zif, zifelse, zindex, zpop, zroll, zsub
  229. };
  230. typedef enum {
  231.     tx_op_add = tx_op,
  232.     tx_op_def,
  233.     tx_op_dup,
  234.     tx_op_exch,
  235.     tx_op_if,
  236.     tx_op_ifelse,
  237.     tx_op_index,
  238.     tx_op_pop,
  239.     tx_op_roll,
  240.     tx_op_sub,
  241.     tx_next_op
  242. } special_op_types;
  243. #define num_special_ops ((int)tx_next_op - tx_op)
  244. const int gs_interp_num_special_ops = num_special_ops; /* for iinit.c */
  245. const int tx_next_index = tx_next_op;
  246.  
  247. /* A null procedure. */
  248. #define make_null_proc(pref)\
  249.   make_empty_const_array(pref, a_executable + a_readonly)
  250. static ref null_proc;
  251.  
  252. /* Initialize the interpreter */
  253. void
  254. gs_interp_init(void)
  255. {    /* Initialize the stacks. */
  256.     gs_ref_memory_t *smem = iimemory_system;
  257.     ref stk;
  258.     ref euop;
  259.     ref *next_body;
  260.     uint refs_size_ostack, refs_size_estack, refs_size_dstack;
  261.  
  262.     if ( gs_debug_c('+') )
  263.       refs_size_ostack = os_refs_size(min_block_ostack),
  264.       refs_size_estack = es_refs_size(min_block_estack),
  265.       refs_size_dstack = ds_refs_size(min_block_dstack);
  266.     else
  267.       refs_size_ostack = os_refs_size(MAX_OSTACK),
  268.       refs_size_estack = es_refs_size(MAX_ESTACK),
  269.       refs_size_dstack = ds_refs_size(MAX_DSTACK);
  270. #if stacks_are_segmented
  271.     next_body = static_stacks.bodies;
  272.     make_array(&ref_static_stacks, avm_system,
  273.            countof(static_stacks.bodies), next_body);
  274.     refset_null(next_body, countof(static_stacks.bodies));
  275. #else
  276.     make_empty_array(&ref_static_stacks, 0);
  277.       {    ref sdata;
  278.         gs_alloc_ref_array(smem, &sdata, 0,
  279.                    refs_size_ostack + refs_size_estack +
  280.                      refs_size_dstack, "interp_init");
  281.         next_body = sdata.value.refs;
  282.       }
  283. #endif
  284. #define alloc_init_stack(stk, i, n)\
  285.   make_array(&stk, avm_system, n, next_body),\
  286.   next_body += (n),\
  287.   make_struct(&ref_ref_stacks[i], avm_system,\
  288.           gs_alloc_struct((gs_memory_t *)smem, ref_stack, &st_ref_stack,\
  289.                   "alloc_init_stack"))
  290.  
  291.     alloc_init_stack(stk, 0, refs_size_ostack);
  292.     ref_stack_init(&o_stack, &stk, os_guard_under, os_guard_over, NULL,
  293.                smem);
  294.     o_stack.underflow_error = e_stackunderflow;
  295.     o_stack.overflow_error = e_stackoverflow;
  296.     ref_stack_set_max_count(&o_stack, MAX_OSTACK);
  297.  
  298.     alloc_init_stack(stk, 1, refs_size_estack);
  299.     make_oper(&euop, 0, estack_underflow);
  300.     ref_stack_init(&e_stack, &stk, es_guard_under, es_guard_over, &euop,
  301.                smem);
  302.     e_stack.underflow_error = e_ExecStackUnderflow;
  303.     e_stack.overflow_error = e_execstackoverflow;
  304.     /**************** E-STACK EXPANSION IS NYI. ****************/
  305.     e_stack.allow_expansion = false;
  306.     esfile_clear_cache();
  307.     ref_stack_set_max_count(&e_stack, MAX_ESTACK);
  308.  
  309.     alloc_init_stack(stk, 2, refs_size_dstack);
  310.     ref_stack_init(&d_stack, &stk, 0, 0, NULL, smem);
  311.     d_stack.underflow_error = e_dictstackunderflow;
  312.     d_stack.overflow_error = e_dictstackoverflow;
  313.     ref_stack_set_max_count(&d_stack, MAX_DSTACK);
  314. }
  315. void
  316. gs_interp_reset(void)
  317. {    /* Reset the stacks. */
  318.     ref_stack_clear(&o_stack);
  319.     ref_stack_clear(&e_stack);
  320.     esp++;
  321.     make_oper(esp, 0, interp_exit);
  322.     ref_stack_pop_to(&d_stack, min_dstack_size);
  323.     dict_set_top();
  324. }
  325. /* Report an e-stack block underflow.  The bottom guard slots of */
  326. /* e-stack blocks contain a pointer to this procedure. */
  327. private int
  328. estack_underflow(os_ptr op)
  329. {    return e_ExecStackUnderflow;
  330. }
  331.  
  332. /*
  333.  * Create an operator during initialization.
  334.  * If operator is hard-coded into the interpreter,
  335.  * assign it a special type and index.
  336.  */
  337. void
  338. gs_interp_make_oper(ref *opref, op_proc_p proc, int idx)
  339. {     register int i = num_special_ops;
  340.       while ( --i >= 0 && proc != special_ops[i] )
  341.     ;
  342.       if ( i >= 0 )
  343.         make_tasv(opref, tx_op + i, a_executable, i + 1, opproc, proc);
  344.       else
  345.         make_tasv(opref, t_operator, a_executable, idx, opproc, proc);
  346. }
  347.  
  348. /*
  349.  * Invoke the interpreter.  If execution completes normally, return 0.
  350.  * If an error occurs, the action depends on user_errors as follows:
  351.  *    user_errors < 0: always return an error code.
  352.  *    user_errors >= 0: let the PostScript machinery handle all errors.
  353.  *    (This will eventually result in a fatal error if no 'stopped'
  354.  *    is active.)
  355.  * In case of a quit or a fatal error, also store the exit code.
  356.  */
  357. private int gs_call_interp(P4(ref *, int, int *, ref *));
  358. int
  359. gs_interpret(ref *pref, int user_errors, int *pexit_code, ref *perror_object)
  360. {    gs_gc_root_t error_root;
  361.     int code;
  362.  
  363.     gs_register_ref_root(imemory_system, &error_root,
  364.                  (void **)&perror_object, "gs_interpret");
  365.     /* Initialize the error object in case of GC. */
  366.     make_null(perror_object);
  367.     code = gs_call_interp(pref, user_errors, pexit_code, perror_object);
  368.     gs_unregister_root(imemory_system, &error_root, "gs_interpret");
  369.     /* Avoid a dangling reference to a stack-allocated GC signal. */
  370.     set_gc_signal(NULL, 0);
  371.     return code;
  372. }
  373. private int
  374. gs_call_interp(ref *pref, int user_errors, int *pexit_code, ref *perror_object)
  375. {    ref *epref = pref;
  376.     ref doref;
  377.     ref *perrordict;
  378.     ref error_name;
  379.     int code, ccode;
  380.     ref saref;
  381.     int gc_signal = 0;
  382.  
  383.     *pexit_code = 0;
  384.     ialloc_reset_requested(idmemory);
  385. again:    o_stack.requested = e_stack.requested = d_stack.requested = 0;
  386.     while ( gc_signal )
  387.       {    /* Some routine below triggered a GC. */
  388.         gs_gc_root_t epref_root;
  389.  
  390.         gc_signal = 0;
  391.         /* Make sure that doref will get relocated properly if */
  392.         /* a garbage collection happens with epref == &doref. */
  393.         gs_register_ref_root(imemory_system, &epref_root,
  394.                      (void **)&epref,
  395.                      "gs_call_interpret(epref)");
  396.         code = (*idmemory->reclaim)(idmemory, -1);
  397.         gs_unregister_root(imemory_system, &epref_root,
  398.                    "gs_call_interpret(epref)");
  399.         if ( code < 0 )
  400.           return code;
  401.       }
  402.     code = interp(epref, perror_object);
  403.     /* Prevent a dangling reference to the GC signal in ticks_left */
  404.     /* in the frame of interp, but be prepared to do a GC if */
  405.     /* an allocation in this routine asks for it. */
  406.     set_gc_signal(&gc_signal, 1);
  407.     if ( esp < esbot )            /* popped guard entry */
  408.       esp = esbot;
  409.     switch ( code )
  410.     {
  411.     case e_Fatal:
  412.         *pexit_code = 255;
  413.         return code;
  414.     case e_Quit:
  415.         *perror_object = osp[-1];
  416.         *pexit_code = code = osp->value.intval;
  417.         osp -= 2;
  418.         return
  419.           (code == 0 ? e_Quit :
  420.            code < 0 && code > -100 ? code : e_Fatal);
  421.     case e_InterpreterExit:
  422.         return 0;
  423.     case e_ExecStackUnderflow:
  424.         /****** WRONG -- must keep mark blocks intact ******/
  425.         ref_stack_pop_block(&e_stack);
  426.         doref = *perror_object;
  427.         epref = &doref;
  428.         goto again;
  429.     case e_VMreclaim:
  430.         /* Do the GC and continue. */
  431.         code = (*idmemory->reclaim)(idmemory,
  432.                         (osp->value.intval == 2 ?
  433.                          avm_global : avm_local));
  434.         /****** What if code < 0? ******/
  435.         make_oper(&doref, 0, zpop);
  436.         epref = &doref;
  437.         goto again;
  438.     case e_NeedInput:
  439.         return code;
  440.     }
  441.     /* Adjust osp in case of operand stack underflow */
  442.     if ( osp < osbot - 1 )
  443.       osp = osbot - 1;
  444.     /* We have to handle stack over/underflow specially, because */
  445.     /* we might be able to recover by adding or removing a block. */
  446.     switch ( code )
  447.       {
  448.     case e_dictstackoverflow:
  449.         if ( ref_stack_extend(&d_stack, d_stack.requested) >= 0 )
  450.           {    dict_set_top();
  451.             doref = *perror_object;
  452.             epref = &doref;
  453.             goto again;
  454.           }
  455.         if ( osp >= ostop )
  456.           {    if ( (ccode = ref_stack_extend(&o_stack, 1)) < 0 )
  457.               return ccode;
  458.           }
  459.         ccode = copy_stack(&d_stack, &saref);
  460.         if ( ccode < 0 )
  461.           return ccode;
  462.         ref_stack_pop_to(&d_stack, min_dstack_size);
  463.         dict_set_top();
  464.         *++osp = saref;
  465.         break;
  466.     case e_dictstackunderflow:
  467.         if ( ref_stack_pop_block(&d_stack) >= 0 )
  468.           {    dict_set_top();
  469.             doref = *perror_object;
  470.             epref = &doref;
  471.             goto again;
  472.           }
  473.         break;
  474.     case e_execstackoverflow:
  475.         /* We don't have to handle this specially: */
  476.         /* The only places that could generate it */
  477.         /* use check_estack, which does a ref_stack_extend, */
  478.         /* so if we get this error, it's a real one. */
  479.         if ( osp >= ostop )
  480.           {    if ( (ccode = ref_stack_extend(&o_stack, 1)) < 0 )
  481.               return ccode;
  482.           }
  483.         ccode = copy_stack(&e_stack, &saref);
  484.         if ( ccode < 0 )
  485.           return ccode;
  486.         {    uint count = ref_stack_count(&e_stack);
  487.             long limit = ref_stack_max_count(&e_stack) - 10;
  488.             if ( count > limit )
  489.               pop_estack(count - limit);
  490.         }
  491.         *++osp = saref;
  492.         break;
  493.     case e_stackoverflow:
  494.         if ( ref_stack_extend(&o_stack, o_stack.requested) >= 0 )
  495.           {    /* We can't just re-execute the object, because */
  496.             /* it might be a procedure being pushed as a */
  497.             /* literal.  We check for this case specially. */
  498.             doref = *perror_object;
  499.             if ( r_is_proc(&doref) )
  500.               {    *++osp = doref;
  501.                 make_null_proc(&doref);
  502.               }
  503.             epref = &doref;
  504.             goto again;
  505.           }
  506.         ccode = copy_stack(&o_stack, &saref);
  507.         if ( ccode < 0 ) return ccode;
  508.         ref_stack_clear(&o_stack);
  509.         *++osp = saref;
  510.         break;
  511.     case e_stackunderflow:
  512.         if ( ref_stack_pop_block(&o_stack) >= 0 )
  513.           {    doref = *perror_object;
  514.             epref = &doref;
  515.             goto again;
  516.           }
  517.         break;
  518.       }
  519.     if ( user_errors < 0 )
  520.       return code;
  521.     if ( gs_errorname(code, &error_name) < 0 )
  522.       return code;        /* out-of-range error code! */
  523.     if ( dict_find_string(systemdict, "errordict", &perrordict) <= 0 ||
  524.          dict_find(perrordict, &error_name, &epref) <= 0
  525.        )
  526.       return code;        /* error name not in errordict??? */
  527.     doref = *epref;
  528.     epref = &doref;
  529.     /* Push the error object on the operand stack if appropriate. */
  530.     if ( !error_is_interrupt(code) )
  531.       *++osp = *perror_object;
  532.     goto again;
  533. }    
  534. private int
  535. interp_exit(os_ptr op)
  536. {    return e_InterpreterExit;
  537. }
  538.  
  539. /* Set the GC signal for all VMs. */
  540. private void
  541. set_gc_signal(int *psignal, int value)
  542. {    gs_memory_gc_status_t stat;
  543.     int i;
  544.     for ( i = 0; i < countof(idmemory->spaces.indexed); i++ )
  545.       {    gs_ref_memory_t *mem = idmemory->spaces.indexed[i];
  546.         if ( mem != 0 )
  547.           {    gs_memory_gc_status(mem, &stat);
  548.             stat.psignal = psignal;
  549.             stat.signal_value = value;
  550.             gs_memory_set_gc_status(mem, &stat);
  551.           }
  552.       }
  553. }
  554.  
  555.  
  556. /* Copy the contents of an overflowed stack into a (local) array. */
  557. private int
  558. copy_stack(const ref_stack *pstack, ref *arr)
  559. {    uint size = ref_stack_count(pstack);
  560.     uint save_space = ialloc_space(idmemory);
  561.     int code;
  562.     ialloc_set_space(idmemory, avm_local);
  563.     code = ialloc_ref_array(arr, a_all, size, "copy_stack");
  564.     if ( code >= 0 )
  565.       code = ref_stack_store(pstack, arr, size, 0, 1, true, "copy_stack");
  566.     ialloc_set_space(idmemory, save_space);
  567.     return code;
  568. }
  569.  
  570. /* Get the name corresponding to an error number. */
  571. int
  572. gs_errorname(int code, ref *perror_name)
  573. {    ref *perrordict, *pErrorNames;
  574.     if ( dict_find_string(systemdict, "errordict", &perrordict) <= 0 ||
  575.          dict_find_string(systemdict, "ErrorNames", &pErrorNames) <= 0
  576.        )
  577.       return_error(e_undefined); /* errordict or ErrorNames not found?! */
  578.     return array_get(pErrorNames, (long)(-code - 1), perror_name);
  579. }
  580.  
  581. /* Store an error string in $error.errorinfo. */
  582. /* This routine is here because of the proximity to the error handler. */
  583. int
  584. gs_errorinfo_put_string(const char *str)
  585. {    ref rstr;
  586.     ref *pderror;
  587.     int code = string_to_ref(str, &rstr, iimemory, "gs_errorinfo_put_string");
  588.     if ( code < 0 )
  589.         return code;
  590.     if ( dict_find_string(systemdict, "$error", &pderror) <= 0 ||
  591.          !r_has_type(pderror, t_dictionary) ||
  592.          dict_put_string(pderror, "errorinfo", &rstr) < 0
  593.        )
  594.         return_error(e_Fatal);
  595.     return 0;
  596. }
  597.  
  598. /* Main interpreter. */
  599. /* If execution terminates normally, return e_InterpreterExit. */
  600. /* If an error occurs, leave the current object in *perror_object */
  601. /* and return a (negative) error code. */
  602. private int
  603. interp(ref *pref /* object to interpret */, ref *perror_object)
  604. {    /*
  605.      * Note that iref is declared as a ref *, but it may actually be
  606.      * a ref_packed *.
  607.      */
  608.     register const ref *iref = pref;
  609.     register int icount = 0;    /* # of consecutive tokens at iref */
  610.     register os_ptr iosp = osp;    /* private copy of osp */
  611.     register es_ptr iesp = esp;    /* private copy of esp */
  612.     int code;
  613.     ref token;        /* token read from file or string, */
  614.                 /* must be declared in this scope */
  615.     register const ref *pvalue;
  616.     os_ptr whichp;
  617.     /*
  618.      * We have to make the error information into a struct;
  619.      * otherwise, the Watcom compiler will assign it to registers
  620.      * strictly on the basis of textual frequency.
  621.      * We also have to use ref_assign_inline everywhere, and
  622.      * avoid direct assignments of refs, so that esi and edi
  623.      * will remain available on Intel processors.
  624.      */
  625.     struct interp_error_s {
  626.         int code;
  627.         int line;
  628.         const ref *obj;
  629.         ref full;
  630.     } ierror;
  631.     /*
  632.      * Get a pointer to the name table so that we can use the
  633.      * inline version of name_index_ref.
  634.      */
  635.     const name_table *int_nt = the_name_table();
  636. #define set_error(ecode)\
  637.   { ierror.code = ecode; ierror.line = __LINE__; }
  638. #define return_with_error(ecode, objp)\
  639.   { set_error(ecode); ierror.obj = objp; goto rwe; }
  640. #define return_with_error_iref(ecode)\
  641.   { set_error(ecode); goto rwei; }
  642. #define return_with_code_iref()\
  643.   { ierror.line = __LINE__; goto rweci; }
  644. #define return_with_error_code_op(nargs)\
  645.   return_with_code_iref()
  646. #define return_with_stackoverflow(objp)\
  647.   { o_stack.requested = 1; return_with_error(e_stackoverflow, objp); }
  648. #define return_with_stackoverflow_iref()\
  649.   { o_stack.requested = 1; return_with_error_iref(e_stackoverflow); }
  650.     int ticks_left = gs_interp_time_slice_ticks;
  651.  
  652.     /*
  653.      * If we exceed the VMThreshold, set ticks_left to -1
  654.      * to alert the interpreter that we need to garbage collect.
  655.      */
  656.     set_gc_signal(&ticks_left, -100);
  657.  
  658.     esfile_clear_cache();
  659.     /*
  660.      * From here on, if icount > 0, iref and icount correspond
  661.      * to the top entry on the execution stack: icount is the count
  662.      * of sequential entries remaining AFTER the current one.
  663.      */
  664. #define add1_short(pref) (const ref *)((const ushort *)(pref) + 1)
  665. #define add1_either(pref) (r_is_packed(pref) ? add1_short(pref) : (pref) + 1)
  666. #define store_state(ep)\
  667.   ( icount > 0 ? (ep->value.const_refs = iref + 1, r_set_size(ep, icount)) : 0 )
  668. #define store_state_short(ep)\
  669.   ( icount > 0 ? (ep->value.const_refs = add1_short(iref), r_set_size(ep, icount)) : 0 )
  670. #define store_state_either(ep)\
  671.   ( icount > 0 ? (ep->value.const_refs = add1_either(iref), r_set_size(ep, icount)) : 0 )
  672. #define next()\
  673.   if ( --icount > 0 ) { iref++; goto top; } else goto out
  674. #define next_short()\
  675.   if ( --icount <= 0 ) { if ( icount < 0 ) goto up; iesp--; }\
  676.   iref = add1_short(iref); goto top
  677. #define next_either()\
  678.   if ( --icount <= 0 ) { if ( icount < 0 ) goto up; iesp--; }\
  679.   iref = add1_either(iref); goto top
  680.  
  681. #if !PACKED_SPECIAL_OPS
  682. #  undef next_either
  683. #  define next_either() next()
  684. #  undef store_state_either
  685. #  define store_state_either(ep) store_state(ep)
  686. #endif
  687.  
  688.     /* We want to recognize executable arrays here, */
  689.     /* so we push the argument on the estack and enter */
  690.     /* the loop at the bottom. */
  691.     if ( iesp >= estop ) return_with_error(e_execstackoverflow, pref);
  692.     ++iesp;
  693.     ref_assign_inline(iesp, pref);
  694.     goto bot;
  695. top:    /*
  696.      * This is the top of the interpreter loop.
  697.      * iref points to the ref being interpreted.
  698.      * Note that this might be an element of a packed array,
  699.      * not a real ref: we carefully arranged the first 16 bits of
  700.      * a ref and of a packed array element so they could be distinguished
  701.      * from each other.  (See ghost.h and packed.h for more detail.)
  702.      */
  703. #ifdef DEBUG
  704.     /* Do a little validation on the top o-stack entry. */
  705.     if ( iosp >= osbot &&
  706.          (r_type(iosp) == t__invalid || r_type(iosp) >= tx_next_op)
  707.        )
  708.       {    lprintf("Invalid value on o-stack!\n");
  709.         return_with_error_iref(e_Fatal);
  710.       }
  711. if ( gs_debug['I'] ||
  712.      (gs_debug['i'] &&
  713.       (r_is_packed(iref) ?
  714.        r_packed_is_name((const ref_packed *)iref) :
  715.        r_has_type(iref, t_name)))
  716.    )
  717.    {    void debug_print_ref(P1(const ref *));
  718.     os_ptr save_osp = osp;        /* avoid side-effects */
  719.     es_ptr save_esp = esp;
  720.     int edepth;
  721.     char depth[10];
  722.     osp = iosp;
  723.     esp = iesp;
  724.     edepth = ref_stack_count(&e_stack);
  725.     sprintf(depth, "%2d", edepth);
  726.     dputs(depth);
  727.     for ( edepth -= strlen(depth); edepth >= 5; edepth -= 5 )
  728.       dputc('*');        /* indent */
  729.     for ( ; edepth > 0; --edepth )
  730.       dputc('.');
  731.     dprintf3("0x%lx(%d)<%d>: ",
  732.          (ulong)iref, icount, ref_stack_count(&o_stack));
  733.     debug_print_ref(iref);
  734.     if ( iosp >= osbot )
  735.        {    dputs(" // ");
  736.         debug_print_ref(iosp);
  737.        }
  738.     dputc('\n');
  739.     osp = save_osp;
  740.     esp = save_esp;
  741.     fflush(dstderr);
  742.    }
  743. #endif
  744. /* Objects that have attributes (arrays, dictionaries, files, and strings) */
  745. /* use lit and exec; other objects use plain and plain_exec. */
  746. #define lit(t) type_xe_value(t, a_execute)
  747. #define exec(t) type_xe_value(t, a_execute + a_executable)
  748. #define nox(t) type_xe_value(t, 0)
  749. #define nox_exec(t) type_xe_value(t, a_executable)
  750. #define plain(t) type_xe_value(t, 0)
  751. #define plain_exec(t) type_xe_value(t, a_executable)
  752.     /*
  753.      * We have to populate enough cases of the switch statement to force
  754.      * some compilers to use a dispatch rather than a testing loop.
  755.      * What a nuisance!
  756.      */
  757.     switch ( r_type_xe(iref) )
  758.        {
  759.     /* Access errors. */
  760. #define cases_invalid()\
  761.   case plain(t__invalid): case plain_exec(t__invalid)
  762.     cases_invalid():
  763.         return_with_error_iref(e_Fatal);
  764. #define cases_nox()\
  765.   case nox_exec(t_array): case nox_exec(t_dictionary):\
  766.   case nox_exec(t_file): case nox_exec(t_string):\
  767.   case nox_exec(t_mixedarray): case nox_exec(t_shortarray)
  768.     cases_nox():
  769.         return_with_error_iref(e_invalidaccess);
  770.     /*
  771.      * Literal objects.  We have to enumerate all the types.
  772.      * In fact, we have to include some extra plain_exec entries
  773.      * just to populate the switch.  We break them up into groups
  774.      * to avoid overflowing some preprocessors.
  775.      */
  776. #define cases_lit_1()\
  777.   case lit(t_array): case nox(t_array):\
  778.   case plain(t_boolean): case plain_exec(t_boolean):\
  779.   case lit(t_dictionary): case nox(t_dictionary)
  780. #define cases_lit_2()\
  781.   case lit(t_file): case nox(t_file):\
  782.   case plain(t_fontID): case plain_exec(t_fontID):\
  783.   case plain(t_integer): case plain_exec(t_integer):\
  784.   case plain(t_mark): case plain_exec(t_mark)
  785. #define cases_lit_3()\
  786.   case plain(t_name):\
  787.   case plain(t_null):\
  788.   case plain(t_oparray):\
  789.   case plain(t_operator)
  790. #define cases_lit_4()\
  791.   case plain(t_real): case plain_exec(t_real):\
  792.   case plain(t_save): case plain_exec(t_save):\
  793.   case lit(t_string): case nox(t_string)
  794. #define cases_lit_5()\
  795.   case lit(t_mixedarray): case nox(t_mixedarray):\
  796.   case lit(t_shortarray): case nox(t_shortarray):\
  797.   case plain(t_device): case plain_exec(t_device):\
  798.   case plain(t_struct): case plain_exec(t_struct):\
  799.   case plain(t_astruct): case plain_exec(t_astruct)
  800.     /* Executable arrays are treated as literals in direct execution. */
  801. #define cases_lit_array()\
  802.   case exec(t_array): case exec(t_mixedarray): case exec(t_shortarray)
  803.     cases_lit_1():
  804.     cases_lit_2():
  805.     cases_lit_3():
  806.     cases_lit_4():
  807.     cases_lit_5():
  808.     cases_lit_array():
  809.         break;
  810.     /* Special operators. */
  811.     case plain_exec(tx_op_add):
  812. x_add:        if ( (code = zop_add(iosp)) < 0 )
  813.           return_with_error_code_op(2);
  814.         iosp--;
  815.         next_either();
  816.     case plain_exec(tx_op_def):
  817. x_def:        if ( (code = zop_def(iosp)) < 0 )
  818.           return_with_error_code_op(2);
  819.         iosp -= 2;
  820.         next_either();
  821.     case plain_exec(tx_op_dup):
  822. x_dup:        if ( iosp < osbot )
  823.           return_with_error_iref(e_stackunderflow);
  824.         if ( iosp >= ostop )
  825.           return_with_stackoverflow_iref();
  826.         iosp++;
  827.         ref_assign_inline(iosp, iosp - 1);
  828.         next_either();
  829.     case plain_exec(tx_op_exch):
  830. x_exch:        if ( iosp <= osbot )
  831.           return_with_error_iref(e_stackunderflow);
  832.         ref_assign_inline(&token, iosp);
  833.         ref_assign_inline(iosp, iosp - 1);
  834.         ref_assign_inline(iosp - 1, &token);
  835.         next_either();
  836.     case plain_exec(tx_op_if):
  837. x_if:        if ( !r_has_type(iosp - 1, t_boolean) )
  838.           return_with_error_iref((iosp <= osbot ?
  839.                       e_stackunderflow : e_typecheck));
  840.         if ( !r_is_proc(iosp) )
  841.           return_with_error_iref(check_proc_failed(iosp));
  842.         if ( !iosp[-1].value.boolval )
  843.           { iosp -= 2;
  844.             next_either();
  845.           }
  846.         if ( iesp >= estop )
  847.           return_with_error_iref(e_execstackoverflow);
  848.         store_state_either(iesp);
  849.         whichp = iosp;
  850.         iosp -= 2;
  851.         goto ifup;
  852.     case plain_exec(tx_op_ifelse):
  853. x_ifelse:    if ( !r_has_type(iosp - 2, t_boolean) )
  854.           return_with_error_iref((iosp < osbot + 2 ?
  855.                       e_stackunderflow : e_typecheck));
  856.         if ( !r_is_proc(iosp - 1) )
  857.           return_with_error_iref(check_proc_failed(iosp - 1));
  858.         if ( !r_is_proc(iosp) )
  859.           return_with_error_iref(check_proc_failed(iosp));
  860.         if ( iesp >= estop )
  861.           return_with_error_iref(e_execstackoverflow);
  862.         store_state_either(iesp);
  863.         whichp = (iosp[-2].value.boolval ? iosp - 1 : iosp);
  864.         iosp -= 3;
  865.         /* Open code "up" for the array case(s) */
  866. ifup:        if ( (icount = r_size(whichp) - 1) <= 0 )
  867.            {    if ( icount < 0 ) goto up;    /* 0-element proc */
  868.             iref = whichp->value.refs;    /* 1-element proc */
  869.             if ( --ticks_left > 0 )
  870.               goto top;
  871.            }
  872.         ++iesp;
  873.         /* Do a ref_assign, but also set iref. */
  874.         iesp->tas = whichp->tas;
  875.         iref = iesp->value.refs = whichp->value.refs;
  876.         if ( --ticks_left > 0 )
  877.           goto top;
  878.         goto slice;
  879.     case plain_exec(tx_op_index):
  880. x_index:    osp = iosp;    /* zindex references o_stack */
  881.         if ( (code = zindex(iosp)) < 0 )
  882.           return_with_error_code_op(1);
  883.         next_either();
  884.     case plain_exec(tx_op_pop):
  885. x_pop:        if ( iosp < osbot )
  886.           return_with_error_iref(e_stackunderflow);
  887.         iosp--;
  888.         next_either();
  889.     case plain_exec(tx_op_roll):
  890. x_roll:        osp = iosp;    /* zroll references o_stack */
  891.         if ( (code = zroll(iosp)) < 0 )
  892.           return_with_error_code_op(2);
  893.         iosp -= 2;
  894.         next_either();
  895.     case plain_exec(tx_op_sub):
  896. x_sub:        if ( (code = zop_sub(iosp)) < 0 )
  897.           return_with_error_code_op(2);
  898.         iosp--;
  899.         next_either();
  900.     /* Executable types. */
  901.     case plain_exec(t_null):
  902.         goto bot;
  903.     case plain_exec(t_oparray):
  904.         /* Replace with the definition and go again. */
  905.         pvalue = (const ref *)iref->value.const_refs;
  906. opst:        /* Prepare to call a t_oparray procedure in *pvalue. */
  907.         store_state(iesp);
  908. oppr:        /* Record the stack depths in case of failure. */
  909.         if ( iesp >= estop - 3 )
  910.           return_with_error_iref(e_execstackoverflow);
  911.         iesp += 4;
  912.         osp = iosp;    /* ref_stack_count_inline needs this */
  913.         make_mark_estack(iesp - 3, es_other, oparray_cleanup);
  914.         make_int(iesp - 2, ref_stack_count_inline(&o_stack));
  915.         make_int(iesp - 1, ref_stack_count_inline(&d_stack));
  916.         make_op_estack(iesp, oparray_pop);
  917.         goto pr;
  918. prst:        /* Prepare to call the procedure (array) in *pvalue. */
  919.         store_state(iesp);
  920. pr:        /* Call the array in *pvalue.  State has been stored. */
  921.         if ( (icount = r_size(pvalue) - 1) <= 0 )
  922.            {    if ( icount < 0 ) goto up;    /* 0-element proc */
  923.             iref = pvalue->value.refs;    /* 1-element proc */
  924.             if ( --ticks_left > 0 )
  925.               goto top;
  926.            }
  927.         if ( iesp >= estop )
  928.           return_with_error_iref(e_execstackoverflow);
  929.         ++iesp;
  930.         /* Do a ref_assign, but also set iref. */
  931.         iesp->tas = pvalue->tas;
  932.         iref = iesp->value.refs = pvalue->value.refs;
  933.         if ( --ticks_left > 0 )
  934.           goto top;
  935.         goto slice;
  936.     case plain_exec(t_operator):
  937.         if ( --ticks_left <= 0 )
  938.           {    /* The following doesn't work, */
  939.             /* and I can't figure out why. */
  940.             /****** goto sst; ******/
  941.           }
  942.         esp = iesp;        /* save for operator */
  943.         osp = iosp;        /* ditto */
  944.         /* Operator routines take osp as an argument. */
  945.         /* This is just a convenience, since they adjust */
  946.         /* osp themselves to reflect the results. */
  947.         /* Operators that (net) push information on the */
  948.         /* operand stack must check for overflow: */
  949.         /* this normally happens automatically through */
  950.         /* the push macro (in oper.h). */
  951.         /* Operators that do not typecheck their operands, */
  952.         /* or take a variable number of arguments, */
  953.         /* must check explicitly for stack underflow. */
  954.         /* (See oper.h for more detail.) */
  955.         /* Note that each case must set iosp = osp: */
  956.         /* this is so we can switch on code without having to */
  957.         /* store it and reload it (for dumb compilers). */
  958.         switch ( code = call_operator(real_opproc(iref), iosp) )
  959.            {
  960.         case 0:            /* normal case */
  961.         case 1:            /* alternative success case */
  962.             iosp = osp;
  963.             next();
  964.         case o_push_estack:    /* store the state and go to up */
  965.             store_state(iesp);
  966. opush:            iosp = osp;
  967.             iesp = esp;
  968.             if ( --ticks_left > 0 )
  969.               goto up;
  970.             goto slice;
  971.         case o_pop_estack:    /* just go to up */
  972. opop:            iosp = osp;
  973.             if ( esp == iesp ) goto bot;
  974.             iesp = esp;
  975.             goto up;
  976.         case o_reschedule:
  977.             store_state(iesp);
  978.             goto res;
  979.         case e_InsertProc:
  980.             store_state(iesp);
  981. oeinsert:        ref_assign_inline(iesp + 1, iref);
  982.             /* esp = iesp + 2; *esp = the procedure */
  983.             iesp = esp;
  984.             goto up;
  985.            }
  986.         iosp = osp;
  987.         iesp = esp;
  988.         return_with_code_iref();
  989.     case plain_exec(t_name):
  990.         pvalue = iref->value.pname->pvalue;
  991.         if ( !pv_valid(pvalue) )
  992.         {    uint nidx = name_index(iref);
  993.             uint htemp;
  994.             if ( (pvalue = dict_find_name_by_index_inline(nidx, htemp)) == 0 )
  995.               return_with_error_iref(e_undefined);
  996.         }
  997.         /* Dispatch on the type of the value. */
  998.         /* Again, we have to over-populate the switch. */
  999.         switch ( r_type_xe(pvalue) )
  1000.            {
  1001.         cases_invalid():
  1002.             return_with_error_iref(e_Fatal);
  1003.         cases_nox():    /* access errors */
  1004.             return_with_error_iref(e_invalidaccess);
  1005.         cases_lit_1():
  1006.         cases_lit_2():
  1007.         cases_lit_3():
  1008.         cases_lit_4():
  1009.         cases_lit_5():
  1010.             /* Just push the value */
  1011.             if ( iosp >= ostop )
  1012.               return_with_stackoverflow(pvalue);
  1013.             ++iosp;
  1014.             ref_assign_inline(iosp, pvalue);
  1015.             next();
  1016.         case exec(t_array):
  1017.         case exec(t_mixedarray):
  1018.         case exec(t_shortarray):
  1019.             /* This is an executable procedure, execute it. */
  1020.             goto prst;
  1021.         case plain_exec(tx_op_add): goto x_add;
  1022.         case plain_exec(tx_op_def): goto x_def;
  1023.         case plain_exec(tx_op_dup): goto x_dup;
  1024.         case plain_exec(tx_op_exch): goto x_exch;
  1025.         case plain_exec(tx_op_if): goto x_if;
  1026.         case plain_exec(tx_op_ifelse): goto x_ifelse;
  1027.         case plain_exec(tx_op_index): goto x_index;
  1028.         case plain_exec(tx_op_pop): goto x_pop;
  1029.         case plain_exec(tx_op_roll): goto x_roll;
  1030.         case plain_exec(tx_op_sub): goto x_sub;
  1031.         case plain_exec(t_null):
  1032.             goto bot;
  1033.         case plain_exec(t_oparray):
  1034.             pvalue = (const ref *)pvalue->value.const_refs;
  1035.             goto opst;
  1036.         case plain_exec(t_operator):
  1037.            {    /* Shortcut for operators. */
  1038.             /* See above for the logic. */
  1039.             if ( --ticks_left <= 0 )
  1040.               {    /* The following doesn't work, */
  1041.                 /* and I can't figure out why. */
  1042.                 /****** goto sst; ******/
  1043.               }
  1044.             esp = iesp;
  1045.             osp = iosp;
  1046.             switch ( code = call_operator(real_opproc(pvalue), iosp) )
  1047.                {
  1048.             case 0:            /* normal case */
  1049.             case 1:            /* alternative success case */
  1050.                 iosp = osp;
  1051.                 next();
  1052.             case o_push_estack:
  1053.                 store_state(iesp);
  1054.                 goto opush;
  1055.             case o_pop_estack:
  1056.                 goto opop;
  1057.             case o_reschedule:
  1058.                 store_state(iesp);
  1059.                 goto res;
  1060.             case e_InsertProc:
  1061.                 store_state(iesp);
  1062.                 goto oeinsert;
  1063.                }
  1064.             iosp = osp;
  1065.             iesp = esp;
  1066.             return_with_error(code, pvalue);
  1067.            }
  1068.         case plain_exec(t_name):
  1069.         case exec(t_file):
  1070.         case exec(t_string):
  1071.         default:
  1072.             /* Not a procedure, reinterpret it. */
  1073.             store_state(iesp);
  1074.             icount = 0;
  1075.             iref = pvalue;
  1076.             goto top;
  1077.            }
  1078.     case exec(t_file):
  1079.        {    /* Executable file.  Read the next token and interpret it. */
  1080.            stream *s;
  1081.         scanner_state sstate;
  1082.         check_read_known_file(s, iref, return_with_error_iref);
  1083. rt:        if ( iosp >= ostop )    /* check early */
  1084.           return_with_stackoverflow_iref();
  1085.         osp = iosp;        /* scan_token uses ostack */
  1086.         scanner_state_init(&sstate, false);
  1087. again:        code = scan_token(s, &token, &sstate);
  1088.         iosp = osp;        /* ditto */
  1089.         switch ( code )
  1090.            {
  1091.         case 0:            /* read a token */
  1092.             /* It's worth checking for literals, which make up */
  1093.             /* the majority of input tokens, before storing the */
  1094.             /* state on the e-stack.  Note that because of //, */
  1095.             /* the token may have *any* type and attributes. */
  1096.             /* Note also that executable arrays aren't executed */
  1097.             /* at the top level -- they're treated as literals. */
  1098.             if ( !r_has_attr(&token, a_executable) ||
  1099.                  r_is_array(&token)
  1100.                )
  1101.               {    /* If scan_token used the o-stack, */
  1102.                 /* we know we can do a push now; if not, */
  1103.                 /* the pre-check is still valid. */
  1104.                 iosp++;
  1105.                 ref_assign_inline(iosp, &token);
  1106.                 goto rt;
  1107.               }
  1108.             store_state(iesp);
  1109.             /* Push the file on the e-stack */
  1110.             if ( iesp >= estop )
  1111.               return_with_error_iref(e_execstackoverflow);
  1112.             esfile_set_cache(++iesp);
  1113.             ref_assign_inline(iesp, iref);
  1114.             iref = &token;
  1115.             icount = 0;
  1116.             goto top;
  1117.         case scan_EOF:        /* end of file */
  1118.             esfile_clear_cache();
  1119.             goto bot;
  1120.         case scan_BOS:
  1121.             /* Binary object sequences */
  1122.             /* ARE executed at the top level. */
  1123.             store_state(iesp);
  1124.             /* Push the file on the e-stack */
  1125.             if ( iesp >= estop )
  1126.               return_with_error_iref(e_execstackoverflow);
  1127.             esfile_set_cache(++iesp);
  1128.             ref_assign_inline(iesp, iref);
  1129.             pvalue = &token;
  1130.             goto pr;
  1131.         case scan_Refill:
  1132.             store_state(iesp);
  1133.             /* iref may point into the exec stack; */
  1134.             /* save its referent now. */
  1135.             ref_assign_inline(&token, iref);
  1136.             /* Push the file on the e-stack */
  1137.             if ( iesp >= estop )
  1138.               return_with_error_iref(e_execstackoverflow);
  1139.             ++iesp;
  1140.             ref_assign_inline(iesp, &token);
  1141.             esp = iesp;
  1142.             osp = iosp;
  1143.             code = scan_handle_refill(&token, &sstate, true, true,
  1144.                           ztokenexec_continue);
  1145.             iosp = osp;
  1146.             iesp = esp;
  1147.             switch ( code )
  1148.               {
  1149.               case 0:
  1150.                 iesp--;        /* don't push the file */
  1151.                 goto again;    /* stacks are unchanged */
  1152.               case o_push_estack:
  1153.                 esfile_clear_cache();
  1154.                 if ( --ticks_left > 0 )
  1155.                     goto up;
  1156.                 goto slice;
  1157.               }
  1158.             /* must be an error */
  1159.             iesp--;        /* don't push the file */
  1160.         default:        /* error */
  1161.             return_with_code_iref();
  1162.            }
  1163.        }
  1164.     case exec(t_string):
  1165.        {    /* Executable string.  Read a token and interpret it. */
  1166.         stream ss;
  1167.         scanner_state sstate;
  1168.         scanner_state_init(&sstate, true);
  1169.         sread_string(&ss, iref->value.bytes, r_size(iref));
  1170.         osp = iosp;        /* scan_token uses ostack */
  1171.         code = scan_token(&ss, &token, &sstate);
  1172.         iosp = osp;        /* ditto */
  1173.         switch ( code )
  1174.           {
  1175.         case 0:            /* read a token */
  1176.         case scan_BOS:        /* binary object sequence */
  1177.             store_state(iesp);
  1178.             /* If the updated string isn't empty, push it back */
  1179.             /* on the e-stack. */
  1180.             { uint size = sbufavailable(&ss);
  1181.               if ( size )
  1182.             { if ( iesp >= estop )
  1183.                 return_with_error_iref(e_execstackoverflow);
  1184.               ++iesp;
  1185.               iesp->tas.type_attrs = iref->tas.type_attrs;
  1186.               iesp->value.const_bytes = sbufptr(&ss);
  1187.               r_set_size(iesp, size);
  1188.             }
  1189.             }
  1190.             if ( code == 0 )
  1191.             {    iref = &token;
  1192.             icount = 0;
  1193.             goto top;
  1194.             }
  1195.             /* Handle BOS specially */
  1196.             pvalue = &token;
  1197.             goto pr;
  1198.         case scan_EOF:        /* end of string */
  1199.             goto bot;
  1200.         case scan_Refill:    /* error */
  1201.             code = gs_note_error(e_syntaxerror);
  1202.         default:        /* error */
  1203.             return_with_code_iref();
  1204.           }
  1205.        }
  1206.     /* Handle packed arrays here by re-dispatching. */
  1207.     /* This also picks up some anomalous cases of non-packed arrays. */
  1208.     default:
  1209.       {    uint index;
  1210.         switch ( *(const ushort *)iref >> r_packed_type_shift )
  1211.         {
  1212.         case pt_full_ref:
  1213.         case pt_full_ref+1:
  1214.             if ( iosp >= ostop )
  1215.               return_with_stackoverflow_iref();
  1216.             /* We know this can't be an executable object */
  1217.             /* requiring special handling, so we just push it. */
  1218.             ++iosp;
  1219.             /* We know that refs are properly aligned: */
  1220.             /* see packed.h for details. */
  1221.             ref_assign_inline(iosp, iref);
  1222.             next();
  1223.         case pt_executable_operator:
  1224.             index = *(const ushort *)iref & packed_value_mask;
  1225.             if ( --ticks_left <= 0 )
  1226.               {    /* The following doesn't work, */
  1227.                 /* and I can't figure out why. */
  1228.                 /****** goto sst_short; ******/
  1229.               }
  1230.             if ( !op_index_is_operator(index) )
  1231.             {    store_state_short(iesp);
  1232.                 /* Call the operator procedure. */
  1233.                 index -= op_def_count;
  1234.                 pvalue = (const ref *)
  1235.                   (index < r_size(&op_array_table_global.table) ?
  1236.                    op_array_table_global.table.value.const_refs +
  1237.                      index :
  1238.                    op_array_table_local.table.value.const_refs +
  1239.                      (index - r_size(&op_array_table_global.table)));
  1240.                 goto oppr;
  1241.             }
  1242.             /* See the main plain_exec(t_operator) case */
  1243.             /* for details of what happens here. */
  1244. #if PACKED_SPECIAL_OPS
  1245.             /* We arranged in iinit.c that the special ops */
  1246.             /* have operator indices starting at 1. */
  1247. #  define case_xop(xop) case xop - tx_op + 1
  1248.             switch ( index )
  1249.               {
  1250.               case_xop(tx_op_add): goto x_add;
  1251.               case_xop(tx_op_def): goto x_def;
  1252.               case_xop(tx_op_dup): goto x_dup;
  1253.               case_xop(tx_op_exch): goto x_exch;
  1254.               case_xop(tx_op_if): goto x_if;
  1255.               case_xop(tx_op_ifelse): goto x_ifelse;
  1256.               case_xop(tx_op_index): goto x_index;
  1257.               case_xop(tx_op_pop): goto x_pop;
  1258.               case_xop(tx_op_roll): goto x_roll;
  1259.               case_xop(tx_op_sub): goto x_sub;
  1260.               case 0:    /* for dumb compilers */
  1261.               default:
  1262.                 ;
  1263.               }
  1264. #  undef case_xop
  1265. #endif
  1266.             esp = iesp;
  1267.             osp = iosp;
  1268.             switch ( code = call_operator(op_index_proc(index), iosp) )
  1269.                {
  1270.             case 0:
  1271.             case 1:
  1272.                 iosp = osp;
  1273.                 next_short();
  1274.             case o_push_estack:
  1275.                 store_state_short(iesp);
  1276.                 goto opush;
  1277.             case o_pop_estack:
  1278.                 iosp = osp;
  1279.                 if ( esp == iesp )
  1280.                    {    next_short();
  1281.                    }
  1282.                 iesp = esp;
  1283.                 goto up;
  1284.             case o_reschedule:
  1285.                 store_state_short(iesp);
  1286.                 goto res;
  1287.             case e_InsertProc:
  1288.                 store_state_short(iesp);
  1289.                 packed_get((const ref_packed *)iref, iesp + 1);
  1290.                 /* esp = iesp + 2; *esp = the procedure */
  1291.                 iesp = esp;
  1292.                 goto up;
  1293.                }
  1294.             iosp = osp;
  1295.             iesp = esp;
  1296.             return_with_code_iref();
  1297.         case pt_integer:
  1298.             if ( iosp >= ostop )
  1299.               return_with_stackoverflow_iref();
  1300.             ++iosp;
  1301.             make_int(iosp,
  1302.                  (*(const short *)iref & packed_int_mask) +
  1303.                  packed_min_intval);
  1304.             next_short();
  1305.         case pt_literal_name:
  1306.           {    uint nidx = *(const ushort *)iref & packed_value_mask;
  1307.             if ( iosp >= ostop )
  1308.               return_with_stackoverflow_iref();
  1309.             ++iosp;
  1310.             name_index_ref_inline(int_nt, nidx, iosp);
  1311.             next_short();
  1312.           }
  1313.         case pt_executable_name:
  1314.           {    uint nidx =
  1315.               (uint)*(const ushort *)iref & packed_value_mask;
  1316.             pvalue = name_index_ptr_inline(int_nt, nidx)->pvalue;
  1317.             if ( !pv_valid(pvalue) )
  1318.                {    uint htemp;
  1319.                 if ( (pvalue = dict_find_name_by_index_inline(nidx, htemp)) == 0 )
  1320.                   {    name_index_ref(nidx, &token);
  1321.                     return_with_error(e_undefined, &token);
  1322.                   }
  1323.                }
  1324.             if ( r_has_masked_attrs(pvalue, a_execute, a_execute + a_executable) )
  1325.               {    /* Literal, push it. */
  1326.                 if ( iosp >= ostop )
  1327.                   return_with_stackoverflow_iref();
  1328.                 ++iosp;
  1329.                 ref_assign_inline(iosp, pvalue);
  1330.                 next_short();
  1331.               }
  1332.             if ( r_is_proc(pvalue) )
  1333.                {    /* This is an executable procedure, */
  1334.                 /* execute it. */
  1335.                 store_state_short(iesp);
  1336.                 goto pr;
  1337.                }
  1338.             /* Not a literal or procedure, reinterpret it. */
  1339.             store_state_short(iesp);
  1340.             icount = 0;
  1341.             iref = pvalue;
  1342.             goto top;
  1343.           }
  1344.         /* default can't happen here */
  1345.         }
  1346.       }
  1347.     }
  1348.     /* Literal type, just push it. */
  1349.     if ( iosp >= ostop )
  1350.       return_with_stackoverflow_iref();
  1351.     ++iosp;
  1352.     ref_assign_inline(iosp, iref);
  1353. bot:    next();
  1354. out:    /* At most 1 more token in the current procedure. */
  1355.     /* (We already decremented icount.) */
  1356.     if ( !icount )
  1357.        {    /* Pop the execution stack for tail recursion. */
  1358.         iesp--;
  1359.         iref++;
  1360.         goto top;
  1361.        }
  1362. up:    if ( --ticks_left < 0 )
  1363.       goto slice;
  1364.     /* See if there is anything left on the execution stack. */
  1365.     if ( !r_is_proc(iesp) )
  1366.        {    iref = iesp--;
  1367.         icount = 0;
  1368.         goto top;
  1369.        }
  1370.     iref = iesp->value.refs;        /* next element of array */
  1371.     icount = r_size(iesp) - 1;
  1372.     if ( icount <= 0 )        /* <= 1 more elements */
  1373.        {    iesp--;            /* pop, or tail recursion */
  1374.         if ( icount < 0 ) goto up;
  1375.        }
  1376.     goto top;
  1377. res:    /* Some operator has asked for context rescheduling. */
  1378.     /* We've done a store_state. */
  1379.     code = (*gs_interp_reschedule_proc)();
  1380. sched:    /* We've just called a scheduling procedure. */
  1381.     /* The interpreter state is in memory; iref is not current. */
  1382.     if ( code < 0 )
  1383.     {    set_error(code);
  1384.         make_null_proc(&null_proc);
  1385.         ierror.obj = iref = &null_proc;
  1386.         goto error_exit;
  1387.     }
  1388.     /* Reload state information from memory. */
  1389.     iosp = osp;
  1390.     iesp = esp;
  1391.     goto up;
  1392. #if 0            /****** ****** ******/
  1393. sst:    /* Time-slice, but push the current object first. */
  1394.     store_state(iesp);
  1395.     if ( iesp >= estop )
  1396.       return_with_error_iref(e_execstackoverflow);
  1397.     iesp++;
  1398.     ref_assign_inline(iesp, iref);
  1399. #endif            /****** ****** ******/
  1400. slice:    /* It's time to time-slice or garbage collect. */
  1401.     /* iref is not live, so we don't need to do a store_state. */
  1402.     osp = iosp;
  1403.     esp = iesp;
  1404.     /* If ticks_left <= -100, we need to GC now. */
  1405.     if ( ticks_left <= -100 )
  1406.       {    /* We need to garbage collect now. */
  1407.         code = (*idmemory->reclaim)(idmemory, -1);
  1408.       }
  1409.     else
  1410.         code = (*gs_interp_time_slice_proc)();
  1411.     ticks_left = gs_interp_time_slice_ticks;
  1412.     goto sched;
  1413.  
  1414.     /* Error exits. */
  1415.  
  1416. rweci:
  1417.     ierror.code = code;
  1418. rwei:
  1419.     ierror.obj = iref;
  1420. rwe:
  1421.     if ( !r_is_packed(iref) )
  1422.       store_state(iesp);
  1423.     else
  1424.       {    /* We need a real object to return as the error object. */
  1425.         /* (It only has to last long enough to store in *perror_object.) */
  1426.         packed_get((const ref_packed *)ierror.obj, &ierror.full);
  1427.         store_state_short(iesp);
  1428.         if ( iref == ierror.obj )
  1429.           iref = &ierror.full;
  1430.         ierror.obj = &ierror.full;
  1431.       }
  1432. error_exit:
  1433.     if ( error_is_interrupt(ierror.code) )
  1434.     {    /* We must push the current object being interpreted */
  1435.         /* back on the e-stack so it will be re-executed. */
  1436.         /* Currently, this is always an executable operator, */
  1437.         /* but it might be something else someday if we check */
  1438.         /* for interrupts in the interpreter loop itself. */
  1439.         if ( iesp >= estop )
  1440.             code = e_execstackoverflow;
  1441.         else
  1442.         {    iesp++;
  1443.             ref_assign_inline(iesp, iref);
  1444.         }
  1445.     }
  1446.     esp = iesp;
  1447.     osp = iosp;
  1448.     ref_assign_inline(perror_object, ierror.obj);
  1449.     return gs_log_error(ierror.code, __FILE__, ierror.line);
  1450.  
  1451. }
  1452.  
  1453. /* Pop the bookkeeping information for a normal exit from a t_oparray. */
  1454. private int
  1455. oparray_pop(os_ptr op)
  1456. {    esp -= 3;
  1457.     return o_pop_estack;
  1458. }
  1459.  
  1460. /* Restore the stack pointers after an error inside a t_oparray procedure. */
  1461. /* This procedure is called only from pop_estack. */
  1462. private int
  1463. oparray_cleanup(os_ptr op)
  1464. {    /* esp points just below the cleanup procedure. */
  1465.     es_ptr ep = esp;
  1466.     uint ocount_old = (uint)ep[2].value.intval;
  1467.     uint dcount_old = (uint)ep[3].value.intval;
  1468.     uint ocount = ref_stack_count(&o_stack);
  1469.     uint dcount = ref_stack_count(&d_stack);
  1470.  
  1471.     if ( ocount > ocount_old )
  1472.       ref_stack_pop(&o_stack, ocount - ocount_old);
  1473.     if ( dcount > dcount_old )
  1474.       ref_stack_pop(&d_stack, dcount - dcount_old);
  1475.     return 0;
  1476. }
  1477.  
  1478. /* ------ Initialization procedure ------ */
  1479.  
  1480. BEGIN_OP_DEFS(interp_op_defs) {
  1481.         /* Internal operators */
  1482.     {"0%interp_exit", interp_exit},
  1483.     {"0%oparray_pop", oparray_pop},
  1484. END_OP_DEFS(0) }
  1485.